<script setup>
import { ref, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {
  vegeFruAddService,
  vegeFruGetDetailService,
  vegeFruEditService,
  GetCategoryService
} from '@/api/vegeFru'
import axios from 'axios'
const formRef = ref()
const defaultForm = {
  name: '',
  mt: '',
  st: '',
  des: '',
  url: '',
  suggestion: '',
  alias: '',
  family: '',
  light: '',
  soilTypes: '',
  soilPh: '',
  reproductivePeriod: '',
  oldImg: ''
}
const visibleDrawer = ref(false)
const imgUrl = ref('')
const desRef = ref()
const sugRef = ref()
const formModel = ref({ ...defaultForm })
//文件在线预览
const onUploadFile = (uploadFile) => {
  console.log(uploadFile)
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.url = uploadFile.raw
}
const open = async (row) => {
  visibleDrawer.value = true
  if (row.id) {
    const res = await vegeFruGetDetailService(row.id)
    formModel.value = res.data
    imgUrl.value = res.data.url
    formModel.value.oldImg = res.data.url //编辑刚打开的时候需要存一份原来的图片地址方便后续删除
    const { url } = res.data
    const index = url.lastIndexOf('/')
    const fileName = url.substring(index + 1)
    formModel.value.img = await imageUrlToFile(imgUrl.value, fileName)
  } else {
    formModel.value = { ...defaultForm }
    imgUrl.value = ''
    desRef.value.clear()
    sugRef.value.clear()
  }
}
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(
      url,
      { responseType: 'arraybuffer' },
      { headers: { 'Cache-Control': 'no-cache' } }
    )

    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}

defineExpose({
  open
})
const emit = defineEmits(['success'])

const onPublish = async () => {
  await formRef.value.validate()
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  if (formModel.value.id) {
    await vegeFruEditService(fd)
    // await vegeFruAddService(fd)
    ElMessage.success('编辑成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    await vegeFruAddService(fd)
    ElMessage.success('添加成功,稍后可通过关键词搜索到')
    visibleDrawer.value = false
    emit('success', 'add')
  }
}
//获取品种数据
const categoryList = ref()
const getCategorylList = async () => {
  const res = await GetCategoryService(formModel.value.mt)
  const map = new Map()
  //去重
  let distinctList = res.data.filter((item) => !map.has(item.st) && map.set(item.st, 1))
  categoryList.value = distinctList
}
getCategorylList()

// 监听大分类 改变即改变小分类
const onMtChange = async (mt) => {
  const res = await GetCategoryService(mt)
  categoryList.value = res.data
  formModel.value.st = ''
}

const desLen = ref(0)
const sugLen = ref(0)
//监听输入的description
watch(
  () => formModel.value.des,
  (newValue) => {
    desLen.value = newValue.length
  }
)
watch(
  () => formModel.value.suggestion,
  (newValue) => {
    sugLen.value = newValue.length
  }
)
//配置校验规则
const rules = {
  name: [{ required: true, message: '请输入果蔬名称', trigger: 'blur' }],
  mt: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  st: [{ required: true, message: '请输入品种', trigger: 'blur' }],
  alias: [{ required: true, message: '请输入别名', trigger: 'blur' }],
  family: [{ required: true, message: '请输入科属', trigger: 'blur' }],
  light: [{ required: true, message: '请输入光照需求', trigger: 'blur' }],
  soilTypes: [{ required: true, message: '请输入土壤类型', trigger: 'blur' }],
  soilPh: [{ required: true, message: '请输入土壤PH', trigger: 'blur' }],
  reproductivePeriod: [{ required: true, message: '请输入生育期', trigger: 'blur' }],
  url: [{ required: true, message: '请上传果蔬图片', trigger: 'change' }],
  des: [
    { required: true, message: '请输入描述信息', trigger: 'blur' },
    { max: 400, message: '描述信息不能超过400字', trigger: 'blur' }
  ],
  suggestion: [
    { required: true, message: '请输入种植建议', trigger: 'blur' },
    { max: 500, message: '种植建议不能超过500字', trigger: 'blur' }
  ]
}
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑果蔬' : '添加果蔬'"
    direction="rtl"
    size="50%"
  >
    <!-- 新增果蔬表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px" :rules="rules">
      <el-form-item label="果蔬名称:" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入名称" style="width: 30%"></el-input>
      </el-form-item>
      <el-form-item label="果蔬分类:" prop="mt">
        <el-select v-model="formModel.mt" style="width: 30%" @change="onMtChange($event)">
          <el-option label="水果" value="水果"></el-option>
          <el-option label="蔬菜" value="蔬菜"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品种:" prop="st">
        <el-select v-model="formModel.st" style="width: 30%">
          <el-option
            v-for="item in categoryList"
            :key="item.st"
            :label="item.st"
            :value="item.st"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="别名:" prop="alias">
        <el-input v-model="formModel.alias" placeholder="请输入别名" style="width: 30%"></el-input>
      </el-form-item>
      <el-form-item label="科属:" prop="family">
        <el-input v-model="formModel.family" placeholder="请输入科属" style="width: 30%"></el-input>
      </el-form-item>
      <el-form-item label="光照需求:" prop="light">
        <el-input v-model="formModel.light" placeholder="请输入" style="width: 70%"></el-input>
      </el-form-item>
      <el-form-item label="土壤类型:" prop="soilTypes">
        <el-input v-model="formModel.soilTypes" placeholder="请输入" style="width: 70%"></el-input>
      </el-form-item>
      <el-form-item label="土壤PH:" prop="soilPh">
        <el-input v-model="formModel.soilPh" placeholder="请输入" style="width: 70%"></el-input>
      </el-form-item>
      <el-form-item label="生育期:" prop="reproductivePeriod">
        <el-input
          v-model="formModel.reproductivePeriod"
          placeholder="请输入"
          style="width: 70%"
        ></el-input>
      </el-form-item>
      <el-form-item label="果蔬图片:" prop="url">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述:" prop="des" class="fromItem">
        <el-input
          v-model="formModel.des"
          style="width: 100%"
          :rows="10"
          type="textarea"
          placeholder="请输入相关描述信息"
          ref="desRef"
          show-word-limit
          maxlength="400"
        />
      </el-form-item>
      <el-form-item label="种植建议:" prop="suggestion" class="fromItem">
        <el-input
          v-model="formModel.suggestion"
          style="width: 100%"
          :rows="10"
          type="textarea"
          placeholder="请输入相关种植建议"
          ref="sugRef"
          show-word-limit
          maxlength="500"
        />
      </el-form-item>
      <el-form-item>
        <el-form-item>
          <el-button @click="onPublish()" type="primary">提交</el-button>
        </el-form-item>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.right {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.fromItem {
  margin-bottom: 50px;
}
</style>
